package T7_26;

import com.alibaba.fastjson.*;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.omg.CORBA.portable.InputStream;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test {//写
    public static void main(String[] args) throws Exception{
        List<Map> maps = null;
        Man man = new Man();

        //创建FileReader对象，指定要读取的文件
        FileReader fileReader=new FileReader("src\\T7_26\\account.json");
        //定义一个int类型的变量length，并令其等于零
        int length=0;
        //定义一个stringbulid类型的变量存放读取的字符
        StringBuilder stringBuilder = new StringBuilder();

        //通过循环来判断是否读取到文件的末尾
        while((length=fileReader.read())!=-1) {
            //将读取到的字符加入stringbulider
            stringBuilder.append((char)length);
            /*发现好像没有必要
            switch ((char)length) {
                case '{':
                case '[':
                    stringBuilder.append("\n");

                    break;
                case '}':
                case ']':
                    stringBuilder.append("\n");
                    break;
                case ',':
                    stringBuilder.append("\n");
                    break;
                default:break;
            }

             */

        }


        //关闭流
        fileReader.close();

        System.out.println(stringBuilder);

        man = JSON.parseObject(String.valueOf(stringBuilder),Man.class);

        System.out.println(man.getAccount());
        System.out.println(man.getPassword());

        System.out.println("------------------------------------");

        //写入数据
        man.setAccount("qqzzk");
        man.setPassword("233333");

        //处理数据(格式化)
        //创建数组用于存放单个字符以用于判断在该位置是否要加入\n
        char[] endchar = JSONObject.toJSONString(man).toCharArray();

        StringBuilder endstring = new StringBuilder();

        for(int i=0;i < endchar.length;i++){
            endstring.append(endchar[i]);
            switch (endchar[i]) {
                case '{':
                case '[':
                    endstring.append("\n");
                    break;
                case '}':
                case ']':
                    endstring.insert(endstring.length()-1,"\n");
                    //先删除现在的"}",再加上\n,再加回来"}"(方法已废弃)
                    //endstring.deleteCharAt(endstring.length()-1);
                    //endstring.append("\n");
                    //endstring.append(endchar[i]);
                    break;
                case ',':
                    endstring.append("\n");
                    break;
                default:break;
            }
        }

        //写入格式化后的数据
        FileWriter fileWriter = new FileWriter("src\\T7_26\\account.json");

        fileWriter.write(String.valueOf(endstring));

        fileWriter.close();

        System.out.println("已写入");



    }
}
